<template>
  <div>
    <div class="margin-container-list mar-l-0 mar-r-10">
      <div class="flex goods-list-layer">
        <ul>
          <li class="actived">指定商品</li>
        </ul>
        <div class="flex-item goods-list-ri">
          <!--顶部搜索 -->
          <div class="top-operate-default height-100 align-h-l">
            <div class="search-item">
              <label>商品搜索：</label>
              <el-select v-model="textCol">
                <el-option label="商品名称" value="title"></el-option>
                <el-option label="商品货号" value="goodsCode"></el-option>
                <el-option label="商品条码" value="goodsBarCode"></el-option>
              </el-select>
              <el-input @keyup.enter.native="doSearch" v-model="textValue" placeholder="请输入关键词" style="width: 220px">
              </el-input>
              <label class="mar-l-20">商品分类：</label>
              <span v-if="appType === 11 && enterpriseConfig.categorySeparate == 1">
                <el-cascader v-model="wholesaleCategoryIds" :props="{ checkStrictly: true }" placeholder="选择商品分类"
                  :options="enterpriseConfig.wholesaleCategoryAlias == 1 ? wholesaleCategoryData : categoryData"
                  clearable filterable></el-cascader>
              </span>
              <span v-else>
                <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" :options="categoryData" clearable
                  filterable></el-cascader>
              </span>
              <label class="mar-l-20">商品品牌：</label>
              <el-select v-model="defaultQuery.brandId" clearable placeholder="请选择">
                <el-option v-for="item in brandList" :key="item.brandId" :label="item.brandName" :value="item.brandId">
                </el-option>
              </el-select>
            </div>
            <div class="search-item">
              <label>品牌分类：</label>
              <el-select v-model="defaultQuery.brandCategoryId" clearable placeholder="请选择">
                <el-option v-for="item in brandCategoryList" :key="item.brandCategoryId" :label="item.brandCategoryName"
                  :value="item.brandCategoryId">
                </el-option>
              </el-select>
              <el-button-group class="mar-l-20">
                <el-button type="primary" @click="doSearch">查询</el-button>
                <el-button plain @click="doResetSearch">重置</el-button>
              </el-button-group>
            </div>
          </div>
          <div class="pad-l-10 pad-r-10">
            <!-- 内容列表 -->
            <div class="table-container" v-loading="listLoading" element-loading-text="加载中">
              <div class="goods-index width-210 mar-b-10" :class="(index + 1) % 4 ? 'mar-r-17' : ''"
                v-for="(item, index) in dataList" :key="index">
                <div class="flex cursor-p goods-item" :class="item.show ? 'actived' : ''" @click="doSelect(item)">
                  <div v-if="item.show" class="actived-icon"><img :src="activedIcon" class="width-31 height-31"
                      border="0" /></div>
                  <label><img :src="item.mainImage" class="user-avatar"></label>
                  <div class="font-12 pad-l-8 pad-t-6">
                    <div class="line-2">
                      <template v-if="item.categoryName">
                        <el-tag size="mini" v-if="item.skuFlag == 1" type="danger" effect="light">多</el-tag>
                      </template>
                      {{item.title}}
                    </div>
                    <div class="pad-t-5" v-if="item.skuFlag == 0">
                      ￥{{ appType === 11 ? item.wholesalePrice : item.sellPrice }}</div>
                    <div class="pad-t-5" v-if="item.skuFlag == 1">
                      {{ appType === 11 ? item.wholesalePrice : item.priceRange }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 列表分页 -->
            <div class="pagination mar-t-10 pad-r-10 flex v-align-c">
              <div class="font-12 flex v-align-c">
                <div>
                  <el-checkbox v-model="currentPaged" @change="currentPageEls">选择本页</el-checkbox>
                </div>
                <div class="pad-l-23">已选{{selectNumber}}个商品，共{{total}}个商品</div>
              </div>
              <div class="flex-item"></div>
              <div>
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                  :current-page="searchListQuery.currentPage" :page-sizes="[20, 50, 100]"
                  :page-size="searchListQuery.size" layout="prev, pager, next" :total="total">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    listBrand,
    listBrandCategory
  } from '@/api/user/enterpriseBrand'
  import {
    listSupplierCategory
  } from '@/api/user/supplierCategory'
  import {
    listProvince,
    listCity,
    listDistrict
  } from '@/api/area/area'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  import {
    getGoodsList,
    listGoodsCategory,
    listWholesaleGoodsCategory
  } from '@/api/goods/goods'
  import {
    pagingHomePageWarehouseGoods
  } from '@/api/warehouse/warehouseGoods'
  import activedIcon from '@/assets/images/icon-sel.png'

  export default {
    props: {
      details1: {
        type: Object,
        default: null
      },
      // 10-云店 11-批发小程序
      appType: {
        type: Number,
        default: 10
      },
      homeType: {
        type: Number,
        default: null
      },
      warehouseId: {
        type: String,
        default: null
      }
    },
    data() {
      return {
        // 文本model
        textCol: 'title',
        textValue: '',
        // 商品来源model
        supplierType: '',
        // 供应商地区model
        areaCodes: [],
        // 零售商品分类model
        categoryIds: [],
        // 批发商品分类model
        wholesaleCategoryIds: [],
        // 默认条件
        defaultQuery: {
          currentPage: 1,
          size: 20,
          goodsType: '',
          brandId: '',
          brandCategoryId: '',
          supplierCategoryId: ''
        },
        // 查询条件
        searchListQuery: {},
        // 企业配置参数
        enterpriseConfig: {
          categorySeparate: '0',
          wholesaleCategoryAlias: '0'
        },
        // 序号
        goodsSortNo: null,
        // 零售商品分类集合
        categoryData: [],
        // 批发商品分类集合
        wholesaleCategoryData: [],
        // 品牌集合
        brandList: [],
        // 品牌分类集合
        brandCategoryList: [],
        // 供应商集合
        supplierList: [],
        // 供应商分类集合
        supplierCategoryList: [],
        areaProps: {
          lazy: true,
          checkStrictly: true,
          lazyLoad(node, resolve) {
            const {
              level
            } = node
            if (level === 0) {
              listProvince().then(response => {
                const nodes = response.data.map(item => {
                  return {
                    value: item.areaCode,
                    label: item.areaName,
                    leaf: false
                  }
                })
                resolve(nodes)
              }).catch(() => {})
            } else if (level === 1) {
              listCity(node.data.value).then(response => {
                const nodes = response.data.map(item => {
                  return {
                    value: item.areaCode,
                    label: item.areaName,
                    leaf: false
                  }
                })
                resolve(nodes)
              }).catch(() => {})
            } else {
              listDistrict(node.data.value).then(response => {
                const nodes = response.data.map(item => {
                  return {
                    value: item.areaCode,
                    label: item.areaName,
                    leaf: true
                  }
                })
                resolve(nodes)
              }).catch(() => {})
            }
          }
        },
        total: 0,
        listLoading: true,
        dataList: [],
        multipleSelection: [],
        activedIcon: activedIcon,
        currentPaged: false,
        selectNumber: 0,
        selectedGoodsList: []
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      const enterpriseId = this.getEnterpriseId()
      // 获取企业配置
      getByEnterpriseId(enterpriseId).then((response) => {
        this.enterpriseConfig = response.data
      })
      // 获取零售商品分类
      listGoodsCategory(enterpriseId).then(response => {
        this.categoryData = response.data
      })
      // 获取批发商品分类
      listWholesaleGoodsCategory(enterpriseId).then(response => {
        this.wholesaleCategoryData = response.data
      })
      // 获取供应商列表
      listSupplier({
        enterpriseId: enterpriseId
      }).then(response => {
        this.supplierList = response.data
      })
      // 获取供应商分类列表
      listSupplierCategory({
        enterpriseId: enterpriseId
      }).then(response => {
        this.supplierCategoryList = response.data
      })
      // 获取品牌列表
      listBrand(enterpriseId).then(response => {
        this.brandList = response.data
      })
      // 获取品牌分类列表
      listBrandCategory(enterpriseId).then(response => {
        this.brandCategoryList = response.data
      })
      if (this.homeType === 3) {
        this.getWarehouseGoodsList()
      } else {
        this.initList()
      }
      if (this.details1 !== null && this.details1.goodsList !== undefined) {
        this.selectedGoodsList = this.details1.goodsList
        this.selectNumber = this.selectedGoodsList.length
      }
    },
    mounted() {
      // const that = this
      // this.$bus.$on('selectComponentGoods', function(goodsSortNo) {
      //   that.goodsSortNo = goodsSortNo
      // })
    },
    methods: {
      // 选择本页
      currentPageEls() {
        this.dataList.forEach(item => {
          var totalPage = Math.ceil(this.total / 20)
          var surplusNumber = 20
          if (this.searchListQuery.currentPage === totalPage) {
            surplusNumber = this.total - (totalPage - 1) * 20
          }
          item.show = this.currentPaged
          if (item.show) {
            this.selectNumber = surplusNumber
          } else {
            this.selectNumber = 0
          }
        })
        if (this.currentPaged) {
          this.dataList.forEach(item => {
            let detailForm = {}
            let flag = true
            if (this.selectedGoodsList.length) {
              this.selectedGoodsList.forEach(itemSel => {
                if (item.goodsId === itemSel.goodsId) {
                  flag = false
                } else {
                  detailForm = {
                    goodsSortNo: this.goodsSortNo,
                    title: item.title,
                    goodsId: item.goodsId,
                    imgUrl: item.mainImage,
                    price: this.appType === 11 ? item.wholesalePrice : item.sellPrice,
                    stock: item.stock,
                    salesNum: item.salesNum,
                    distributeIncome: item.distributeIncome,
                    skuFlag: item.skuFlag,
                    anchorRatio: item.anchorRatio,
                    putawayNum: item.putawayNum,
                    anchorGoodsStatus: item.anchorGoodsStatus,
                    anchorPlatformShopType: item.anchorPlatformShopType,
                    quickAuthority: item.quickAuthority,
                    tiktokAuthority: item.tiktokAuthority,
                    income: item.anchorCommission
                  }
                }
              })
              if (flag) {
                this.selectedGoodsList.push(detailForm)
              }
            } else {
              detailForm = {
                goodsSortNo: this.goodsSortNo,
                title: item.title,
                goodsId: item.goodsId,
                imgUrl: item.mainImage,
                price: this.appType === 11 ? item.wholesalePrice : item.sellPrice,
                stock: item.stock,
                salesNum: item.salesNum,
                distributeIncome: item.distributeIncome,
                skuFlag: item.skuFlag,
                anchorRatio: item.anchorRatio,
                putawayNum: item.putawayNum,
                anchorGoodsStatus: item.anchorGoodsStatus,
                anchorPlatformShopType: item.anchorPlatformShopType,
                quickAuthority: item.quickAuthority,
                tiktokAuthority: item.tiktokAuthority,
                income: item.anchorCommission
              }
              this.selectedGoodsList.push(detailForm)
            }
          })
        } else {
          this.dataList.forEach(item => {
            this.selectedGoodsList.splice(this.selectedGoodsList.findIndex(itemSel => item.goodsId === itemSel
              .goodsId), 1)
          })
        }
      },
      // 初始化
      initList() {
        this.listLoading = true
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        // 零售商品分类
        this.searchListQuery.oneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
        // 批发商品分类
        this.searchListQuery.wholesaleOneCategoryId = this.wholesaleCategoryIds.length > 0 ? this.wholesaleCategoryIds[
          0] : ''
        this.searchListQuery.wholesaleTwoCategoryId = this.wholesaleCategoryIds.length > 1 ? this.wholesaleCategoryIds[
          1] : ''
        this.searchListQuery.wholesaleThreeCategoryId = this.wholesaleCategoryIds.length > 2 ? this
          .wholesaleCategoryIds[2] : ''
        // 供应商地区
        this.searchListQuery.supplierProvinceCode = this.areaCodes.length > 0 ? this.areaCodes[0] : ''
        this.searchListQuery.supplierCityCode = this.areaCodes.length > 1 ? this.areaCodes[1] : ''
        this.searchListQuery.supplierDistrictCode = this.areaCodes.length > 2 ? this.areaCodes[2] : ''
        // 应用类型
        switch (this.appType) {
          case 10:
            this.searchListQuery.goodsStatus = '1'
            this.searchListQuery.goodsTypes = '30,32'
            break
          case 11:
            this.searchListQuery.wholesaleGoodsStatus = '1'
            this.searchListQuery.goodsTypes = '31,32'
            break
          case 13:
            this.searchListQuery.goodsStatus = '1'
            this.searchListQuery.goodsTypes = '30,32'
            this.searchListQuery.selectionGoodsType = '1'
            break
          default:
        }
        // 商品来源
        switch (this.supplierType) {
          case 'enterprise':
            this.searchListQuery.goodsSource = '0'
            break
          case 'taobao':
            this.searchListQuery.goodsSource = '2'
            break
          default:
            this.searchListQuery.supplierId = this.supplierType
        }
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        getGoodsList(this.searchListQuery).then(response => {
          this.total = response.total
          this.dataList = response.records
          this.dataList.forEach(item => {
            if (this.selectedGoodsList.length > 0) {
              item.show = this.selectedGoodsList.some(function(goodsDetail) {
                return goodsDetail.goodsId === item.goodsId
              })
            } else {
              item.show = false
            }
          })
          this.listLoading = false
        })
      },
      getWarehouseGoodsList() {
        this.listLoading = true
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.goodsStatus = 1
        this.searchListQuery.authorizeStatus = 1
        this.searchListQuery.warehouseId = this.warehouseId
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.oneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
        pagingHomePageWarehouseGoods(this.searchListQuery).then(response => {
          if (response.isError) return
          this.dataList = response.data.records
          this.dataList.forEach(item => {
            if (this.selectedGoodsList.length > 0) {
              item.show = this.selectedGoodsList.some(function(goodsDetail) {
                return goodsDetail.goodsId === item.goodsId
              })
            } else {
              item.show = false
            }
          })
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        if (this.homeType === 3) {
          this.getWarehouseGoodsList()
        } else {
          this.initList()
        }
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.supplierType = originData.supplierType
        this.areaCodes = originData.areaCodes
        this.categoryIds = originData.categoryIds
        this.wholesaleCategoryIds = originData.wholesaleCategoryIds
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 选择事件
      doSelect(row) {
        console.log('选择11')
        row.show = !row.show
        const changeData = row.show
        this.$delete(row, 'show')
        this.$set(row, 'show', changeData)
        const detailForm = {
          goodsSortNo: this.goodsSortNo,
          title: row.title,
          goodsId: row.goodsId,
          imgUrl: row.mainImage,
          price: this.appType === 11 ? row.wholesalePrice : row.sellPrice,
          stock: row.stock,
          salesNum: row.salesNum,
          distributeIncome: row.distributeIncome,
          skuFlag: row.skuFlag,
          anchorRatio: row.anchorRatio,
          putawayNum: row.putawayNum,
          anchorGoodsStatus: row.anchorGoodsStatus,
          anchorPlatformShopType: row.anchorPlatformShopType,
          quickAuthority: row.quickAuthority,
          tiktokAuthority: row.tiktokAuthority,
          income: row.anchorCommission
        }
        if (row.show) {
          this.selectNumber = this.selectNumber + 1
          this.selectedGoodsList.push(detailForm)
          // this.$bus.$emit('choiceDetailsGoods', detailForm)
        } else {
          this.selectNumber = this.selectNumber - 1
          this.selectedGoodsList.splice(this.selectedGoodsList.findIndex(item => row.goodsId === item.goodsId), 1)
        }
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.currentPaged = false
        this.selectNumber = 0
        this.searchListQuery.currentPage = val
        if (this.homeType === 3) {
          this.getWarehouseGoodsList()
        } else {
          this.initList()
        }
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        if (this.homeType === 3) {
          this.getWarehouseGoodsList()
        } else {
          this.initList()
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .goods-list-layer {
    ul {
      margin: 0 2px 0 0;
      padding: 0;
      display: block;

      li {
        padding: 24px 0;
        font-size: 16px;
        width: 100px;
        text-align: center;
        list-style-type: none;
        color: #666;

        &.actived {
          background: #f8f8f8;
          color: #409eff;
        }
      }
    }

    /deep/ .search-item .el-select .el-input {
      width: 120px !important;
    }

    .goods-list-ri {
      background: #f8f8f8;
    }

    /deep/ .el-table {
      border-top: #e2e2e2 1px solid;
    }

    /deep/ .el-table th,
    /deep/ .el-table tr {
      background: #f8f8f8;
    }

    /deep/ .el-table th:hover,
    /deep/ .el-table tr:hover,
    /deep/ .el-table th:hover>td,
    /deep/ .el-table tr:hover>td {
      background: #f8f8f8 !important;
    }

    /deep/ .el-table td,
    /deep/ .el-table th.is-leaf {
      border-bottom: none;
    }

    /deep/ .el-loading-mask {
      background-color: rgba(255, 255, 255, 0.6) !important;
    }

    .table-container {
      min-height: 380px;

      &:after {
        content: '';
        display: block;
        clear: both;
        font-size: 0;
      }
    }

    .goods-index {
      float: left;
    }

    .goods-item {
      border-radius: 6px;
      background: #fdfffd;
      border: #f8f8f8 1px solid;
      overflow: hidden;
      position: relative;

      &.actived {
        border: #409eff 1px solid;
      }

      .actived-icon {
        position: absolute;
        right: 0;
        bottom: -6px;
      }
    }
  }

  .user-avatar {
    width: 75px;
    height: 75px;
    display: block;
    border-radius: 6px 0 0 6px;
  }

  .category-style {
    color: #3abbdb
  }

  .top-operate-default {
    background: none !important;

    /deep/ .search-item {
      padding: 0;

      label {
        width: 80px;
        text-align: right;
      }

      .el-input {
        width: 150px;
      }
    }
  }

  .align-h-l {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-evenly;
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }
</style>
